using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.Caching;
using Volo.Abp.DependencyInjection;

namespace Joy.Erp.Ufida.Pmc
{
    /// <summary>
    /// 物料供需平衡缓存服务实现
    /// </summary>
    public class MaterialBalanceCacheService : IMaterialBalanceCacheService, ITransientDependency
    {
        private readonly IDistributedCache<List<SupplyDemandRecordDto>> _cache;
        private const string CacheKeyPrefix = "MaterialBalance:SupplyDemand:";

        public MaterialBalanceCacheService(IDistributedCache<List<SupplyDemandRecordDto>> cache)
        {
            _cache = cache;
        }

        private string GetCacheKey(DateTime cutoffDate)
        {
            return $"{CacheKeyPrefix}{cutoffDate:yyyy-MM-dd}";
        }

        public async Task<bool> ExistsAsync(DateTime cutoffDate)
        {
            var cacheKey = GetCacheKey(cutoffDate);
            var data = await _cache.GetAsync(cacheKey);
            return data != null && data.Count > 0;
        }

        public async Task SetSupplyDemandRecordsAsync(
            DateTime cutoffDate,
            List<SupplyDemandRecordDto> records
        )
        {
            var cacheKey = GetCacheKey(cutoffDate);
            await _cache.SetAsync(
                cacheKey,
                records,
                new Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(2), // 缓存2小时
                }
            );
        }

        public async Task<List<SupplyDemandRecordDto>> GetSupplyDemandRecordsAsync(
            DateTime cutoffDate
        )
        {
            var cacheKey = GetCacheKey(cutoffDate);
            var data = await _cache.GetAsync(cacheKey);
            return data ?? new List<SupplyDemandRecordDto>();
        }

        public async Task ClearAsync()
        {
            // 注意：分布式缓存没有清除所有键的直接方法
            // 这里只是一个占位实现，实际使用中可能需要维护键列表或使用其他策略
            await Task.CompletedTask;
        }

        public async Task ClearAsync(DateTime cutoffDate)
        {
            var cacheKey = GetCacheKey(cutoffDate);
            await _cache.RemoveAsync(cacheKey);
        }
    }
}
